/*
 * @lc app=leetcode id=61 lang=cpp
 *
 * [61] Rotate List
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head || !head->next || k < 1) {
            return head;
        }

        ListNode *node = head;
        int len = 0;
        while(node) {
            node = node->next;
            len++;
        }

        if ((k = k % len) == 0) {
            return head;
        }

        node = head;
        while(--len > k) {
            node = node->next;
        }

        ListNode *temp = head;
        head = node->next;
        node->next = NULL;

        node = head;
        while(node && node->next) {
            node = node->next;
        }
        node->next = temp;

        return head;
    }

};

